package com.open.capacity.exam.service.impl;

import com.open.capacity.common.model.*;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.util.RequestUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.exam.dao.*;
import com.open.capacity.exam.feign.GroupFeignClient;
import com.open.capacity.exam.service.ExamService;
import com.open.capacity.exam.vo.CheckPaper;
import com.open.capacity.exam.vo.ExamAnswerVo;
import com.open.capacity.exam.vo.PaperVo;
import com.open.capacity.exam.vo.QuestionsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExamServiceImpl implements ExamService {
    @Autowired
    private ExamAnswerDao answerDao;
    @Autowired
    private PaperUserDao paperUserDao;
    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private PaperQuestionDao paperQuestionDao;
    @Autowired
    private GroupFeignClient groupFeignClient;
    @Autowired
    private PaperDao paperDao;

    /**
     * 根据用户id查询考试
     * @param param
     * @return
     */
    @Override
    public PageResult<PaperVo> findExam(Map<String, Object> param) {
        if(param.containsKey("page")){
            PageUtil.pageParamConver(param,false);
        }else {
            param.put("page",null);
            param.put("limit",null);
        }
        //查询所有考卷
        List<PaperVo> list= paperDao.selectByUser(param);
        int count= paperDao.selectCountByUser(param);
        return PageResult.<PaperVo>builder().data(list).count((long)count).build();
    }
    /**
     * 答题
     * 插入答题信息
     * @param userid 考生用户id
     * @param expaid    试卷id
     * @param quesid 考题id
     * @param answer    考生答案
     * @return
     */
    @Override
    @Transactional
    public Result answer(String userid, Integer expaid, Integer[] quesid, String[] answer) {
        Map<String,Object> map=new HashMap<>();
        map.put("userid",userid);
        map.put("expaid",expaid);
        ExamPaperUser examPaperUser= paperUserDao.select(map);
        if(examPaperUser==null){
            return Result.failed("考试已被移除");
        }
        ExamAnswer examAnswer=new ExamAnswer();
        examAnswer.setPausid(examPaperUser.getPausid());    //学员对应考卷信息
        boolean ifChoose=true;//判断是否只有选择题
        int count=0;
        for (int i = 0; i < quesid.length; i++) {
            examAnswer.setQuesid(quesid[i]);
            examAnswer.setAnswer(answer[i]);
            QuestionsVo param=new QuestionsVo();
            param.setQuesid(quesid[i]);
            //对比选择题答案
            List<QuestionsVo> list = questionDao.findAll(param);
            QuestionsVo standard = list.get(0);
            if(standard.getTpname().contains("选")){
                if(standard.getAnswer().equals(answer[i])){
                    examAnswer.setResult(1);                //答案正确
                }else {
                    examAnswer.setResult(2);                //答案错误
                }
            }else{
                ifChoose=false;
                examAnswer.setResult(-1);
            }
            Integer insert= answerDao.insert(examAnswer);
            if(insert>0){
                count++;
            }
        }
        if(count==quesid.length){
            //修改试卷状态,已完成考试
            if(ifChoose){   //只有选择题
                examPaperUser.setStatus(3);
            }else{
                examPaperUser.setStatus(2);
            }
            paperUserDao.update(examPaperUser);
            //修改考卷状态为：已有人参考
            paperDao.update(expaid);
            return Result.succeed("操作成功");
        }else{
            return Result.failed("出错了");
        }
    }

    /**
     * 查找用户考卷，判断是否是否已经答卷
     * @param param
     * @return
     */
    @Override
    public PageResult<ExamPaperUser> findAnswer(Map<String, Object> param) {
        ExamPaperUser paperUser = paperUserDao.select(param);
        List<ExamPaperUser> list=new ArrayList<>();
        list.add(paperUser);
        return PageResult.<ExamPaperUser>builder().data(list).build();
    }

    /**
     * 查找答题结果
     * @param param userid expaid
     * @return
     */
    @Override
    public PageResult<ExamAnswerVo> findResult(Map<String, Object> param) {
        //获取学生的考卷
        ExamPaperUser paperUser = paperUserDao.select(param);
        Integer pausid = paperUser.getPausid();

        ExamAnswer examAnswer=new ExamAnswer();
        examAnswer.setPausid(pausid);
        //获取学生考卷的信息和答案  和总分数
        double count=0;
        List<ExamAnswerVo> result = answerDao.select(examAnswer);
        for(ExamAnswerVo eav:result){
            //查询试卷考题给的分数
            List<ExamPaperQuestion> pqList = paperQuestionDao.select(paperUser.getExpaid(), eav.getQuesid());
            Integer score = pqList.get(0).getScore();
            eav.setScore(score);
            //获取总分数
            if(eav.getResult()==1){
                count+=score;
            }else if(eav.getResult()==3){
                count+=(score/2);
            }
        }
        return PageResult.<ExamAnswerVo>builder().data(result).count((long)count).build();
    }

    /**
     * 试卷批改
     * 查询教师对应的小组成员 已提交的试卷
     * @param param teacid（教练id）
     * @return
     */
    @Override
    public PageResult<PaperVo> findSubmitExam(Map<String, Object> param) {
        //根据教练id查询所有小组
        PageResult<Group> groupByTeacher = groupFeignClient.getGroupByTeacher(param);
        List<Group> groups = groupByTeacher.getData();
        List<SysUser> userList=new ArrayList<>();
        for(Group group:groups){
            //根据小组id查询所有小组成员
            Map<String,Object> map=new HashMap<>();
            map.put("grouid",group.getGrouid());
            PageResult<SysUser> sysUserPageResult = groupFeignClient.selectUserByGroup(map);
            List<SysUser> users = sysUserPageResult.getData();
            userList.addAll(users);
        }
        //根据用户id查询答卷
        Map<String,Object> map=new HashMap<>();
        if(param.containsKey("status")){
            map.put("status",param.get("status"));
        }
        if(param.containsKey("expaid")){
            map.put("expaid",param.get("expaid"));
        }
        List<PaperVo> paperVoList =new ArrayList<>();
        for(SysUser user:userList){
            map.put("userid",user.getId());
            List<PaperVo> list = paperDao.selectByUser(map);
            //设置用户名和id
            for(PaperVo pv:list){
                pv.setUsername(user.getNickname());
                pv.setUserid(user.getId()+"");
            }
            paperVoList.addAll(list);
        }
        return PageResult.<PaperVo>builder().data(paperVoList).count((long)paperVoList.size()).build();
    }

    /**
     * 批改试卷
     * @param checkPapers 试卷和考生
     * @return
     */
    @Override
    @Transactional
    public Result updateExam(List<CheckPaper> checkPapers) {
        //查询考生试卷关系表
        Map<String,Object> map=new HashMap<>();
        map.put("userid",checkPapers.get(0).getUserid());
        map.put("expaid",checkPapers.get(0).getExpaid());
        ExamPaperUser examPaperUser = paperUserDao.select(map);
        ExamAnswer examAnswer=new ExamAnswer();
        examAnswer.setPausid(examPaperUser.getPausid());
        for (CheckPaper checkPaper:checkPapers) {
           examAnswer.setQuesid(checkPaper.getQuesid());
           examAnswer.setResult(checkPaper.getResult());
           answerDao.update(examAnswer);
        }
        //修改
        examPaperUser.setStatus(3);
        Integer update = paperUserDao.update(examPaperUser);
        return Result.succeed("操作成功");
    }
}

